// src/main/java/com/easy/controller/LoginController.java
package com.easy.controller;

import com.easy.bean.UserAccount;
import com.easy.bean.LoginRequest;
import com.easy.bean.RegisterRequest;
import com.easy.service.LoginService;
import com.easy.util.CaptchaUtil;
import com.easy.util.PasswordUtil;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "http://localhost:5173")
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    // 获取验证码
    @GetMapping("/captcha")
    public Result captcha() {
        System.out.println("开始生成验证码");
        Result result = Result.success(CaptchaUtil.getCaptcha());
        System.out.println("验证码生成结果: " + result);
        return result;
    }

    // 用户登录（带验证码）
    @PostMapping("/dologin")
    public Result login(@RequestBody LoginRequest req) {
        System.out.println("收到登录请求: " + req);
        
        // 验证验证码
        System.out.println("开始验证验证码 - key: " + req.getKey() + ", captcha: " + req.getCaptcha());
        boolean captchaValid = CaptchaUtil.checkCaptcha(req.getKey(), req.getCaptcha());
        System.out.println("验证码验证结果: " + captchaValid);
        
        if (!captchaValid) {
            System.out.println("验证码错误，返回错误信息");
            return Result.fail(500, "验证码错误");
        }

        // 构造 UserAccount 对象
        UserAccount user = new UserAccount();
        user.setUsername(req.getUsername());
        user.setPassword(req.getPassword());  // 使用password字段接收明文密码
        
        System.out.println("构造用户对象: " + user.getUsername());

        try {
            String token = loginService.login(user);
            System.out.println("登录成功，生成token: " + token);
            return Result.success(token);
        } catch (Exception e) {
            System.out.println("登录失败: " + e.getMessage());
            e.printStackTrace();
            return Result.fail(500, e.getMessage());
        }
    }
    
    // 用户注册
    @PostMapping("/register")
    public Result register(@RequestBody RegisterRequest req) {
        // 验证验证码
        if (!CaptchaUtil.checkCaptcha(req.getCaptchaKey(), req.getCaptcha())) {
            return Result.fail(500, "验证码错误");
        }

        // 构造 UserAccount 对象
        UserAccount user = new UserAccount();
        user.setUsername(req.getUsername());
        user.setPassword(req.getPassword());  // 使用password字段接收明文密码
        user.setEmail(req.getEmail());
        user.setRole("user"); // 默认角色为普通用户
        user.setStatus((byte) 1); // 默认状态为启用
        user.setIs_deleted((byte) 0); // 未删除

        try {
            UserAccount registeredUser = loginService.register(user);
            return Result.success(registeredUser);
        } catch (Exception e) {
            return Result.fail(500, e.getMessage());
        }
    }
}